<template>
  <div>
    <van-index-bar :index-list="computedCityList" @select="handleSelect">
      <div v-for="data in cityList" :key="data.type">
        <van-index-anchor :index="data.type"/>
        <van-cell :title="city.name" v-for="(city,index) in data.list" :key="index" @click="handleChangePage(city.cityId,city.name)"/>
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import Vue from 'vue';
import {IndexAnchor, IndexBar, Toast} from 'vant';
import http from "../util/http";
import {mapMutations} from "vuex";


Vue.use(IndexBar);
Vue.use(IndexAnchor);
export default {
  name: "City",
  data () {
    return {
      cityList: [
        /*{
          type: 'A',
          list: ['安庆', '安瑞']
        }, {
          type: 'B',
          list: ['北京', '保定']
        }*/
      ],
    }
  },
  computed: {
    computedCityList() {
      return this.cityList.map(item => item.type) //自定义索引，从数组中过滤出想要的数据，map通过指定函数处理数组的每个元素，并返回处理后的数组。
    }
  },
  mounted() {
    http({
      url: '/gateway?k=2490149',
      method: 'GET',
      headers: {
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then(res => {
      //console.log(res.data.data.cities)
      //将请求的数据进行格式整理
      this.cityList = this.handleCityData(res.data.data.cities)
      //console.log(this.cityList)
    })
  },
  methods: {
    handleCityData(cities) {
      //输入原始数据，输出目标数据
      const letterArr = [] //用于存放26个字母
      const newCityes = [] //用于存放分类好的城市列表
      for (let code = 65; code < 91; code++) {
        letterArr.push(String.fromCharCode(code)) //将ascll码转换成字符
      }
      letterArr.forEach((data) => {
        let list = cities.filter(item=>item.pinyin.substring(0,1).toUpperCase() === data)
        if (list.length > 0) {
          newCityes.push({
            type: data,
            list: list
          })
        }
      })
      return newCityes
    },
    handleSelect(index) {
      //点击索引栏的字符时触发
      Toast(index)
    },
    handleChangePage(cityid,cityname) {
      //console.log(cityid)
      /*this.$store.state.cityId = cityid //将用户选择的城市传到影院组件中，进行数据切换
      this.$store.state.cityName = cityname*/

      //通过提交 mutation 的方式，而非直接改变 store.state.*，是因为我们想要更明确地追踪到状态的变化。
      // this.$store.commit("changeCityName",cityname)
      // this.$store.commit("changeCityId",cityid)
      this.changeCityName(cityname)
      this.changeCityId(cityid)
      this.$router.back()
    },
    ...mapMutations('cityModule',['changeCityName','changeCityId'])
  }
}
</script>

<style scoped>

</style>